//
//  PKPlayerManager.m
//  AVPlayer
//
//  Created by lanou on 15/10/5.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKPlayerManager.h"
#import <AVFoundation/AVFoundation.h>
@interface PKPlayerManager ()

@property (nonatomic, strong) NSArray *musicArray; // 用来保存音乐的地址的数组
@property (nonatomic, strong) AVPlayer *avPlayer; // 音乐播放器
@property (nonatomic, assign) NSInteger playIndex; // 当前播放的音乐的下标

@end

@implementation PKPlayerManager

-(instancetype)init
{
    self = [super init];
    if (self) {
        _avPlayer = [[AVPlayer alloc]init];
    }
    return self;
}

+ (instancetype)sharedManager
{
    static PKPlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PKPlayerManager alloc]init];
        
    });
    return manager;
}

// 给音乐播放器 设置播放音乐的地址的数组
- (void)setManagerMusicArray:(NSArray *)array
{
    _musicArray = array;
}

// 根据外界传过来的下标来播放
- (void)playWithIndex:(NSInteger)index
{
    _playIndex = index;
    NSURL *musicURL = [NSURL URLWithString:_musicArray[index]];
    // 根据传过来的下标选择数组里相应的播放地址
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:musicURL];
    // 把播放器的播放地址替换成新的地址
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    [_avPlayer play];
}

// 下一首
- (void)nextMusic
{
    _playIndex++;
    if (_playIndex == _musicArray.count) {
        _playIndex = 0;
    }
    // 判断如果是随机播放 就随机一个播放下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_playIndex];
} 

// 上一首
- (void)beforeMusic
{
    _playIndex--;
    if (_playIndex < 0) {
        _playIndex = _musicArray.count - 1;
    }
    // 判断如果是随机播放 就随机一个播放下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_playIndex];
}

// 播放/暂停
- (void)playAndPause
{
    // AVPlayer当前的状态 0.0代表停止播放状态 1.0代表正在播放
    if (_avPlayer.rate == 0.0) {
        [_avPlayer play];
    }else
    {
        [_avPlayer pause];
    }
}

-(NSUInteger)finishTime
{
    CMTime time = _avPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}

-(NSUInteger)currentTime
{
    CMTime time = _avPlayer.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}

// 跳转
- (void)seekToTime:(NSUInteger)time
{
    CMTime newTime = _avPlayer.currentTime;
    // 秒 ＝ value / 基数
    newTime.value = newTime.timescale * time;
    
    [_avPlayer seekToTime:newTime];
}

// 停止
- (void)stop
{
    [self seekToTime:0];
    [_avPlayer pause];
}


@end
